package com.akino.gulimall.seckill.interceptor;

import com.akino.common.constant.AuthServerConstant;
import com.akino.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Akino
 * @version 1.0
 * 登陆拦截：等进入订单系统的都必须是已经登陆的用户
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    // 共享数据
    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<>();
    // 前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/kill", uri);
        if (match){
            MemberRespVo attribute = (MemberRespVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
            if (attribute!=null){
                loginUser.set(attribute);
                return true;
            } else {
                // 没登陆就重定向到登陆页面
                response.sendRedirect("http://auth.gulimall.com/login.html");
                return false;
            }
        }
        return true;
    }
}
